package com.wmapp.connect;

/**
 * <p>Title: MCU System mcu.manager</p>
 * <p>Description: Web mcu.manager for MCU System</p>
 * <p>Copyright: Copyright (c) 2003-2005 MCU System</p>
 * <p>Company: MCU System</p>
 * @author MCU System
 * @version 3.0
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
//import java.util.Iterator;
//import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.dom4j.Document;
//import org.dom4j.DocumentHelper;
//import org.dom4j.Element;

//import com.wmapp.domain.Conference;
//import com.wmapp.utils.DomainUtils;
import com.wmapp.utils.SimpleStringUtils;

public class Connection {
	private static Log log=LogFactory.getLog(Connection.class);
	
    private Socket socket;
    private BufferedReader in;
    private BufferedWriter out;
    
    public static final String FAILED="400 FAILED";
    public static final String OK="200 OK";
    public static final String END="300 END";
    public static final String CONTENT_LENGTH="Content_Length: ";

    public Connection(String ip,int port) throws Exception {
        socket = new Socket(ip, port);
        socket.setSoTimeout(10*1000);//twenty seconds
        in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
        out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
    }

    public void sendXML(String content) throws Exception {
        out.write(content);
        out.flush();
        log.debug(content);
    }
    
    public String receiveXML() throws Exception{
    	StringBuffer ret=new StringBuffer();
    	String head = null;
        String contentLength=null;
        
        head=in.readLine();
        
        if(head.equals(FAILED)){
        	contentLength = in.readLine(); // content length
            String reason = in.readLine(); // reason
            log.error(SimpleStringUtils.join("receive xml fail.reason:",reason));
            throw new Exception(reason);
        }else if (head.equals(OK)) {
        	contentLength = in.readLine(); // content length
            String str = CONTENT_LENGTH;
            String strLen = contentLength.substring(str.length());
            int len = Integer.parseInt(strLen); // content length
            if (len > 0) {
                while (true){                    
                    str = in.readLine();
                    if(str.equals(END))
                        break;
                    ret.append(str);
                }
            }
        }else{
        	String reason=SimpleStringUtils.join(head," is unknown head");
        	log.error(reason);
        	throw new Exception(reason);
        }
        
        log.debug(ret);
    	return ret.toString();
    }
    
    public void close(){
    	try {
    		if(socket!=null)
    			socket.close();
    		if(out!=null)
    			out.close();
    		if(in!=null)
    			in.close();
		} catch (IOException e) {
			log.warn("close connection fail.",e);
		}
    }
    
    // The main method for test request
	public static void main(String[] args) throws Exception {
		Connection conn = null;
		conn = new Connection("mymcu.gnway.net", 5040);
		Map map = new HashedMap();
		map.put("id", "1302440607909");
		Request req = new Request(Request.DEL_RESERVATION_REQ,map,"reservation",true);
		conn.sendXML(req.getContent());

		String receive = conn.receiveXML();
		conn.close();
	}
}
